<script setup>
	import {
		ref
	} from 'vue'
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		useCartStore
	} from '@/store'
	import {
		getDefaultAddressApi,
		getAddressListApi
	} from '@/apis/address'
	import {
		getGoodsInfoByIdApi
	} from '@/apis/goods.js'
	import {
		submitOrderApi
	} from '@/apis/order'
	import {
		payApi
	} from '@/apis/pay.js'
	import {
		route
	} from 'uview-plus'

	let flag;
	// 获取立即购买传递过来的 商品id获取商品 或者 获取 pinia 中存储购物项来展示购物列表
	onLoad(async (e) => {
		// const res  = uni.getStorageSync('addressInfo')
		// console.log(res);
		const res = await getDefaultAddressApi()
		addressInfo.value = res.data.data
		flag = uni.getSystemInfoSync().platform === 'android'
		if (flag) {
			var EnvUtils = plus.android.importClass("com.alipay.sdk.app.EnvUtils");
			EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);

		}
		if (e && e.goodsId) {
			console.log(e.goodsId);
			getGoodsInfoById(e.goodsId)
		} else {
			const cartStore = useCartStore()
			goodsList.value = cartStore.cartList.filter(item => item.checked === true)
			totalPrice.value = goodsList.value.reduce((acc, item) => acc + item.sellingPrice * item.goodsCount,
					0)
				.toFixed(2)
		}
	})
	// 获取商品信息
	const getGoodsInfoById = async (id) => {
		const res = await getGoodsInfoByIdApi(id)
		goodsInfo.value = {
			id: null,
			goodsId: res.data.data.id,
			goodsName: res.data.data.goodsName,
			goodsImage: res.data.data.goodsCoverImg,
			sellingPrice: res.data.data.sellingPrice,
			goodsCount: 1
		}
		totalPrice.value = res.data.data.sellingPrice

	}

	// 地址弹层
	const showAddress = ref(false)
	const addressList = ref([])
	const addressInfo = ref({}) // 选择好的地址信息

	// 获取默认地址
	// onShow(async () => {
	// 	const res = await getDefaultAddressApi()
	// 	addressInfo.value = res.data.data
	// })

	const getAddressList = async () => {
		const res = await getAddressListApi()
		addressList.value = res.data.data
	}
	getAddressList()
	// 打开选择地址弹层
	const openAddressPopup = () => {
		showAddress.value = true
	}
	// 选择地址
	const changeCheck = (row) => {
		addressInfo.value = row
		uni.setStorage({
			key: 'addressInfo',
			data: addressInfo.value
		})
		showAddress.value = false
	}

	// 去新增地址
	const toAddAddress = () => {
		console.log('去新增地址');
		// uni.navigateTo({
		// 	url: '/pages/address/addSite'
		// })
	}

	// 购买的商品列表
	const goodsList = ref([])
	const goodsInfo = ref({})
	// 总价格
	const totalPrice = ref(0)
	let orderNo = "";

	// 提交订单，后端返回订单 id
	const handlerSubmitOrder = async () => {

		if (goodsInfo.value.goodsId) {
			const res = await submitOrderApi({
				addressId: addressInfo.value.id,
				goodsId: goodsInfo.value.goodsId
			})

			orderNo = res.data.data
			showPay.value = true
		} else {
			const ids = goodsList.value.map(item => item.id)
			console.log(ids);
			const res = await submitOrderApi({
				addressId: addressInfo.value.id,
				cartItemIds: ids
			})
			orderNo = res.data.data
			showPay.value = true
		}
	}


	// 支付方式弹层
	const showPay = ref(false)
	const handlerPay = async (payType) => { // 提交订单
	if(!flag) {
		uni.showToast({
			title: '当前的环境无法进行支付',
			icon: 'none'
		})
		return
	}
		if (payType === 2) {
			uni.showToast({
				title: '暂不支持微信支付',
				icon: 'none'
			})
			return
		}
	

		// 支付
		const res = await payApi(orderNo)
		console.log(res);
		// uni.showToast({
		// 	title: '支付成功',
		// 	icon: 'none'
		// })
		// showPay.value = false
		// route({
		// 	type: 'redirectTo',
		// 	url: '/pages/order/orderDetails?orderNo=' + orderNo
		// })


		// 支付成功唤起支付宝
		uni.requestPayment({
			provider: 'alipay',
			orderInfo: res.data.data,
			success: (res) => {
				uni.showToast({
					title: '支付成功',
					icon: 'none'
				})
				showPay.value = false
				route({
					type: 'redirectTo',
					url: '/pages/order/orderDetails?orderNo=' + orderNo
				})
			},
			fail: (e) => {
				uni.showToast({
					title: '支付失败',
					icon: 'none'
				})
				showPay.value = false
				route({
					type: 'redirectTo',
					url: '/pages/order/orderDetails?orderNo=' + orderNo
				})
			}
		})



	}


	// 关闭支付
	const closePay = () => {
		showPay.value = false
		route({
			type: 'redirectTo',
			url: '/pages/order/orderDetails?orderNo=' + orderNo
		})

	}
</script>


<template>
	<view class="page">
		<!-- 导航栏 -->
		<view class="nav">
			<up-navbar :autoBack="true" :placeholder="true" border title="提交订单" rightIcon="more-dot-fill">
			</up-navbar>
		</view>


		<view class="container">
			<!-- 头部地址部分 -->
			<view class="head-box">
				<!-- 跳转选择选择地址 -->
				<view class="address-section" @click="openAddressPopup">
					<view v-if="addressInfo && addressInfo.userName">
						<view class="user-info">
							<up-text size="16" :text="`${addressInfo.userName} ${addressInfo.userPhone}`"></up-text>
						</view>
						<view class="address-info" style="margin-top:20rpx;">
							<up-text size="16"
								:text="`${addressInfo.provinceName} ${addressInfo.cityName} ${addressInfo.regionName} ${addressInfo.detailAddress}`"></up-text>
						</view>
					</view>
					<view v-else>
						<up-text size="18" text="暂无地址，去添加地址"></up-text>
					</view>
					<view>
						<up-icon name="arrow-right" size="24"></up-icon>
					</view>
				</view>


			</view>

			<view class="body-box">
				<!-- 购物车列表 -->
				<scroll-view class="goods-section" scroll-y v-if="goodsList && goodsList.length > 0">
					<view class="goods-item" v-for="(item, index) in goodsList" :key="index">
						<up-image width="160rpx" height="160rpx" :src="item.goodsImage"></up-image>
						<view class="goods-info">
							<view class="goods-title">
								<view class="title">{{ item.goodsName }}</view>
								<view>x{{ item.goodsCount }}</view>
							</view>
							<view class="goods-price">
								<up-text color="red" size="18" :text="item.sellingPrice" mode="price"></up-text>
							</view>
						</view>
					</view>
				</scroll-view>

				<!-- 立即购买 -->
				<view v-else>
					<view class="goods-item">
						<up-image width="160rpx" height="160rpx" :src="goodsInfo.goodsImage"></up-image>
						<view class="goods-info">
							<view class="goods-title">
								<view class="title">{{ goodsInfo.goodsName }}</view>
								<view>x{{ goodsInfo.goodsCount }}</view>
							</view>
							<view class="goods-price">
								<up-text color="red" size="18" :text="goodsInfo.sellingPrice" mode="price"></up-text>
							</view>
						</view>
					</view>
				</view>

			</view>

			<!-- 底部：提交订单和总金额 -->
			<view class="footer">
				<view class="total-amount">
					<text>总金额：</text>
					<text class="amount">￥{{ totalPrice }}</text>
				</view>
				<up-button size="large" color="#52ABAD" @click="handlerSubmitOrder">提交订单</up-button>
			</view>
		</view>

		<!-- 地址选择弹层 -->
		<up-popup :show="showAddress" :closeable="true" :round="20" mode="bottom" @close="showAddress=false">
			<view class="popup-address">
				<view class="title">选择收货地址</view>
				<scroll-view class="scroll-H" :scroll-y="true">
					<view class="item" v-for="(item, index) in addressList" :key="item.id">
						<view class="info" @click="changeCheck(item)">
							<view class="address">
								{{ item.provinceName + item.cityName + item.regionName + item.detailAddress }}
							</view>
							<view class="user">{{ item.userName + item.userPhone }}</view>
						</view>
						<view @click="toAddAddress(item.id)">
							<up-icon name="edit-pen" :size="30" color="#999999"></up-icon>
						</view>
					</view>
				</scroll-view>
				<view class="bottom">
					<up-button size="large" color="#52ABAD" @click="toAddAddress(null)">新增收货地址</up-button>
				</view>
			</view>

		</up-popup>


		<!-- 支付方式弹层  -->
		<up-popup :show="showPay" :closeable="true" :round="20" mode="bottom" @close="closePay">
			<view class="popup-pay">
				<up-button size="large" @click="handlerPay(1)" color="#4187F2">支付宝支付</up-button>
				<up-button size="large" @click="handlerPay(2)" color="#6FBE91">微信支付</up-button>
			</view>

		</up-popup>

	</view>
</template>
<style lang="scss" scoped>
	.container {
		background-color: #F9F9F9;
		height: calc(100vh - 250rpx);
	}

	// 地址
	.head-box {
		position: relative;
		background-color: #fff;
		height: 160rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-evenly;
		padding: 20rpx;

		.address-section {
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		&:before {
			width: 100%;
			position: absolute;
			left: 0;
			top: 6rem;
			height: .2rem;
			background: -webkit-repeating-linear-gradient(135deg, #ff6c6c, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
			background: repeating-linear-gradient(-45deg, #ff6c6c, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
			background-size: 2.13333rem;
			content: "";
		}

	}

	.body-box {


		.goods-section {
			padding-top: 20rpx;
			padding-bottom: 70rpx;


		}


		.goods-item {
			margin-bottom: 10rpx;
			padding: 0 20rpx;
			display: flex;
			align-items: center;
			background-color: #fff;

			.goods-info {
				height: 160rpx;
				flex: 1;
				padding: 10rpx 40rpx;
				display: flex;
				flex-direction: column;
				justify-content: space-around;

				.goods-title {
					display: flex;

					.title {
						flex: 1;
					}
				}
			}
		}

	}

	.footer {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		flex-direction: column;
		justify-content: space-evenly;
		background-color: #fff;
		height: 280rpx;
		padding: 0 20rpx;
		border-top: 1px solid #ddd;

		.total-amount {
			display: flex;
			justify-content: space-between;

			.amount {
				color: red;
			}
		}

	}

	// 弹出地址
	.popup-address {
		height: 800rpx;
		width: 100%;

		.title {
			text-align: center;
			font-weight: 600;
			font-size: 30rpx;
			padding: 20rpx 0;
		}

		.scroll-H {
			height: 600rpx;

			.item {
				margin: 0 20rpx;
				display: flex;
				align-items: center;
				border-bottom: 1px solid #ccc;
				height: 140rpx;

				.info {
					margin-left: 10rpx;
					flex: 1;

					.address {
						color: #000;
						font-weight: 600;
						line-height: 60rpx;
					}

					.user {
						color: #827878;
					}
				}
			}
		}

		.bottom {
			padding: 0 30rpx;
		}


	}

	// 弹出支付方式
	.popup-pay {
		display: flex;
		flex-direction: column;
		justify-content: space-evenly;
		padding: 100rpx 30rpx;
		height: 250rpx;
	}
</style>